<?php


namespace app\api\controller\v1;


use app\api\exception\BaseException;
use app\api\validate\GoodsScene;
use app\api\validate\RefundScene;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\Request;

/**
 * Class Refund
 * @package app\api\controller\v1
 * 退款
 *
 * 报销管理 和 退款管理合并为财务管理
 */
class Refund extends BaseException
{
    /**
     * 不需要登录方法
     */
    protected $noAuth = [];

    /**
     * 获取退款列表
     * 数据筛选
     */
    public function getRefundList()
    {
        $data = Request::param();
        $search = [
        ];
        if (isset($data["sort"]) && $data["sort"] == "+id") {
            $order = ["id" => "asc"];
        } else {
            $order = ["id" => "desc"];
        }

        /**
         * 单一模糊查询开始
         */
        //拆包姓名模糊查询
        if (isset($data["unpack_name"]) && !empty($data["unpack_name"])) {
            $search[] = ["unpack_name", "like", "%" . $data["unpack_name"] . "%"];
        }
        //拆包产品名模糊查询
        if (isset($data["unpack_goods_name"]) && !empty($data["unpack_goods_name"])) {
            $search[] = ["unpack_goods_name", "like", "%" . $data["unpack_goods_name"] . "%"];
        }
        //录单姓名
        if (isset($data["record_name"]) && !empty($data["record_name"])) {
            $search[] = ["record_name", "like", "%" . $data["record_name"] . "%"];
        }
        //录单商品名称
        if (isset($data["record_goods"]) && !empty($data["record_goods"])) {
            $search[] = ["record_goods", "like", "%" . $data["record_goods"] . "%"];
        }
        //申请人
        if (isset($data["applicant_name"]) && !empty($data["applicant_name"])) {
            $search[] = ["applicant_name", "like", "%" . $data["applicant_name"] . "%"];
        }
        //销售单号
        if (isset($data["after_sales_id"]) && !empty($data["after_sales_id"])) {
            array_push($search, ["after_sales_id", "=", $data["after_sales_id"]]);
        }
        //拆包电话
        if (isset($data["unpack_telephone"]) && !empty($data["unpack_telephone"])) {
            array_push($search, ["unpack_telephone", "=", $data["unpack_telephone"]]);
        }
        //录单人电话
        if (isset($data["record_telephone"]) && !empty($data["record_telephone"])) {
            array_push($search, ["record_telephone", "=", $data["record_telephone"]]);
        }
        /**
         * 单一模糊查询结束
         */
        /**
         *多条件查询开始
         */
        //数据状态筛选查询
        //  if (isset($data["data_state"]) && $data["data_state"] != '') {
        array_push($search, ["data_state", "=", 1]);
        //}
        if (isset($data["status"]) && $data["status"] != '') {
            array_push($search, ["status", "=", $data["status"]]);
        }
        $goodsClasslist = Db::name("refund")->where($search)->order($order)->page($this->page_num, $this->page_limit)->select()->toArray();
        $count = Db::name("refund")->where($search)->count();
        foreach ($goodsClasslist as $key => $value) {
            $imgsArray = explode(",", $goodsClasslist[$key]["imgs"]);

            $goodsClasslist[$key]["real_imgs"] = $imgsArray;
            if (count($imgsArray) != 0) {
                for ($i = 0; $i < count($imgsArray); $i++) {
                    $imgsArray[$i] = "http://" . $_SERVER['HTTP_HOST'] . $imgsArray[$i];
                }
            }
            $goodsClasslist[$key]["imgs"] = $imgsArray;

        }

        foreach ($goodsClasslist as $key1 => $value1) {
            if ($goodsClasslist[$key1]["order_id"] != 0) {
                $orderGoodsList =  Db::name("order_goods")->where(["order_id" => $goodsClasslist[$key1]["order_id"]])->select()->toArray();
                $str = "";
                for ($i = 0;$i < count($orderGoodsList); $i++ ){
                    if ($i == 0){
                        $str = $orderGoodsList[$i]["goods_name"] . ','.$orderGoodsList[$i]["goods_color"].','.$orderGoodsList[$i]["goods_size"].', x'.$orderGoodsList[$i]["num"];
                    }else{
                        $str = $str."|". $orderGoodsList[$i]["goods_name"] . ','.$orderGoodsList[$i]["goods_color"].','.$orderGoodsList[$i]["goods_size"].', x'.$orderGoodsList[$i]["num"];
                    }
                }
                $orderinfo = Db::name("orders")->where(["id" => $goodsClasslist[$key1]["order_id"]])->find();
                $goodsClasslist[$key1]["record_name"] = $orderinfo["name"];
                $goodsClasslist[$key1]["record_telephone"] = $orderinfo["telephone"];
                $goodsClasslist[$key1]["order_time"] = $orderinfo["create_time"];
                $goodsClasslist[$key1]["record_goods"] = $str;
            }
        }
        $list = [
            "total" => $count,
            "page" => $this->page_num,
            "limit" => $this->page_limit,
            "list" => $goodsClasslist
        ];
        //Db::name("account")->getLastSql();
        return self::Success($list, '获取成功', 200);
    }

    /**
     * 添加退款数据 （单条添加）
     */
    public function addRefundInfo()
    {
        $request = Request::param();
//        try {
//            validate(RefundScene::class)
//                ->scene('add')
//                ->check($request);
//        } catch (ValidateException $e) {
//            // 验证失败 输出错误信息
//            return self::Error(null, $e->getError(), 404);
//        }
        $userinfo = Db::name("account")->where(["id" => $this->user_id])->find();
        $insertData = [
            "user_id" => $this->user_id,
            "order_id" => $request["order_id"],
            "applicant_name" => $userinfo["real_name"],
            "price" => isset($request["price"]) ? $request["price"] : 0,
            "refund_reason" => isset($request["refund_reason"]) ? $request["refund_reason"] : "",
            "imgs" => isset($request["imgs"]) ? $request["imgs"] : "",
            "express_num" => isset($request["express_num"]) ? $request["express_num"] : "",
            "unpack_time" => isset($request["unpack_time"]) ? $request["unpack_time"] : date("Y-m-d H:i:s", time()),
            "unpack_name" => isset($request["unpack_name"]) ? $request["unpack_name"] : "",
            "unpack_telephone" => isset($request["unpack_telephone"]) ? $request["unpack_telephone"] : "",
            "unpack_goods_name" => isset($request["unpack_goods_name"]) ? $request["unpack_goods_name"] : "",
            "after_sales_id" => isset($request["after_sales_id"]) ? $request["after_sales_id"] : "",
            "order_time" => isset($request["order_time"]) ? $request["order_time"] : date("Y-m-d H:i:s", time()),
            "record_name" => isset($request["record_name"]) ? $request["record_name"] : '',
            "record_telephone" => isset($request["record_telephone"]) ? $request["record_telephone"] : '',
            "record_goods" => isset($request["record_goods"]) ? $request["record_goods"] : '',
            "record_price" => isset($request["record_price"]) ? $request["record_price"] : 0,
            'create_time' => date("Y-m-d H:i:s", time()),
            'update_time' => date("Y-m-d H:i:s", time()),
            'data_state' => 1,
            'status' => 0
        ];

        $result = Db::name("refund")->insert($insertData);
        if ($result) {
            return self::Success(null, "添加成功", 200);
        } else {
            return self::Error(null, '添加失败', 10002);
        }
    }

    /**
     * 批量导入退款数据
     */
    public function importRefundInfo()
    {

    }
    public function batchDelete()
    {
        $request = Request::param();
        $ids = explode(",", $request["ids"]);
        if (count($ids) != 0) {
            for ($i = 0; $i < count($ids); $i++) {
                $updateData = [
                    "data_state" => 0,
                    "update_time" => date("Y-m-d H:i:s", time()),
                ];
                Db::name("refund")->where(["id" => $ids[$i]])->update($updateData);
            }
        }
        return self::Success(null, "删除成功", 200);
    }


    /**
     * 批量更新数据状态
     * 可以单一修改
     * 只有财务才能删除
     */
    public function batchUpdateState()
    {
        $request = Request::param();
        try {
            validate(RefundScene::class)
                ->scene('update_state')
                ->check($request);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return self::Error(null, $e->getError(), 404);
        }
        $updateData = [
            "data_state" => $request["data_state"],
            "update_time" => date("Y-m-d H:i:s", time()),
        ];
        $check = Db::name("refund")->where(["id" => $request["id"]])->find();
        if ($check) {
            $result = Db::name("refund")->where(["id" => $request["id"]])->update($updateData);
            if ($result) {
                return self::Success(null, "操作成功", 200);
            } else {
                return self::Error(null, '操作失败', 10002);
            }
        } else {
            return self::Error(null, '数据不存在', 10002);
        }
    }

    /**
     * 只有财务才能修改退款数据
     * 更新退款数据
     */
    public function updateRefundInfo()
    {
        $request = Request::param();
        try {
            validate(GoodsScene::class)
                ->scene('update')
                ->check($request);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return self::Error(null, $e->getError(), 404);
        }
        $updateData = [
            "applicant_name" => isset($request["applicant_name"]) ? $request["applicant_name"] : "",
            "price" => isset($request["price"]) ? $request["price"] : 0,
            "refund_reason" => isset($request["refund_reason"]) ? $request["refund_reason"] : "",
            "imgs" => isset($request["imgs"]) ? $request["imgs"] : "",
            "unpack_time" => isset($request["unpack_time"]) ? $request["unpack_time"] : date("Y-m-d H:i:s", time()),
            "unpack_name" => isset($request["unpack_name"]) ? $request["unpack_name"] : "",
            "unpack_telephone" => isset($request["unpack_telephone"]) ? $request["unpack_telephone"] : "",
            "unpack_goods_name" => isset($request["unpack_goods_name"]) ? $request["unpack_goods_name"] : "",
            "after_sales_id" => isset($request["after_sales_id"]) ? $request["after_sales_id"] : "",
            "order_time" => isset($request["order_time"]) ? $request["order_time"] : date("Y-m-d H:i:s", time()),
            "record_name" => isset($request["record_name"]) ? $request["record_name"] : '',
            "record_telephone" => isset($request["record_telephone"]) ? $request["record_telephone"] : '',
            "record_goods" => isset($request["record_goods"]) ? $request["record_goods"] : '',
            "record_price" => isset($request["record_price"]) ? $request["record_price"] : 0,
            'update_time' => date("Y-m-d H:i:s", time()),
        ];
        $result = Db::name("refund")->where(["id" => $request["id"]])->update($updateData);
        if ($result) {
            return self::Success(null, "更新成功", 200);
        } else {
            return self::Error(null, '更新成功', 10002);
        }

    }

    /**
     * 财务审核退款数据
     * 只有财务人员才能审核
     */
    public function updateRefundStatus()
    {
        $request = Request::param();
        try {
            validate(GoodsScene::class)
                ->scene('update_status')
                ->check($request);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return self::Error(null, $e->getError(), 404);
        }
        if ($request["status"] == 1) {
            $updateData = [
                "status" => $request["status"],
                "pass_time" => date("Y-m-d H:i:s", time()),
                "update_time" => date("Y-m-d H:i:s", time()),
            ];
            Db::name("refund")->where(["id" => $request["id"]])->update($updateData);
        } else {
            $updateData = [
                "status" => $request["status"],
                "update_time" => date("Y-m-d H:i:s", time()),
            ];
            Db::name("refund")->where(["id" => $request["id"]])->update($updateData);
        }

        $check = Db::name("refund")->where(["id" => $request["id"]])->find();

        if ($check) {
            if ($check["order_id"] != 0){
                Db::name("orders")->where(["id" => $check["order_id"]])->update(["order_state" => 4]);
            }
            $updateData =[
                "status" => 1,
                "update_time" =>  date("Y-m-d H:i:s", time())
            ];
            Db::name("after_sales")->where(["id" => $check["after_sales_id"]])->update($updateData);
//            $result = Db::name("refund")->where(["id" => $request["id"]])->update($updateData);
//            if ($result) {
                return self::Success(null, "操作成功", 200);
//            } else {
//                return self::Error(null, '操作失败', 10002);
//            }
        } else {
            return self::Error(null, '数据不存在', 10002);
        }
    }

}